﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Kugar.Core.BaseStruct;
using Kugar.ERPFramework.BLLInterface;
using Kugar.ERPFramework.Entity;
using Kugar.Core.ExtMethod;

namespace Kugar.ERPFramework.View.WinForm
{
    public partial class ModuleDataBrowserBase : ModuleFormBase
    {
        protected object ModuleControler = null;
        protected int GetDataPageSize = 20;
        private BindingList<EntityBase> _cacheDataList = new BindingList<EntityBase>();

        protected ModuleDataBrowserBase()
            : base()
        {
            InitializeComponent();
            dgData.AutoGenerateColumns = false;

            dgData.DataSource = _cacheDataList;
            dgData.AddRowIndex(true);
        }

        public ModuleDataBrowserBase(object controler)
            : this()
        {
            ModuleControler = controler;
        }

        /// <summary>
        ///     是否显示模块分类树
        /// </summary>
        public bool DisplayCategory
        {
            set
            {
                tabCategory.Visible = value;
            }
            get { return tabCategory.Visible; }
        }

        private void ModuleDataBrowserBase_Load(object sender, EventArgs e)
        {
            //控制按钮可见
            btnOpen.Visible = ModuleControler is IOpenable;
            btnDelete.Visible = ModuleControler is IDeletable;
            btnAddnew.Visible = ModuleControler is ICreatable;
            btnExecute.Visible = ModuleControler is IExecutable;
            btnAntiExecute.Visible = ModuleControler is IAntiExecutable;
            btnAudit.Visible = ModuleControler is IAuditable;
            btnAntiAudit.Visible = ModuleControler is IAntiAuditable;
            btnRed.Visible = ModuleControler is IRedable;

            //控制菜单按钮可见
            tsmiOpen.Visible = ModuleControler is IOpenable;
            tsmiDelete.Visible = ModuleControler is IDeletable;
            tsmiAudit.Visible = ModuleControler is IAuditable;
            tsmiAntiAudit.Visible = ModuleControler is IAntiAuditable;
            tsmiExecute.Visible = ModuleControler is IExecutable;
            tsmiAntiExecute.Visible = ModuleControler is IAntiExecutable;
            tsmiRed.Visible = ModuleControler is IRedable;

        }

        #region "操作按钮的对应的实际处理函数"

        /// <summary>
        ///     打开指定单据
        /// </summary>
        /// <param name="data"></param>
        protected virtual ResultReturn OpenEntity(Entity.EntityBase data)
        {
            if (!(ModuleControler is IOpenable))
            {
                return new ResultReturn(false, @"当前模块未实现打开功能");
            }

            var openinter = (IOpenable)ModuleControler;

            if (data != null)
            {
                if(openinter.IsOpenable(data))
                {
                    return new SuccessResuleReturn();
                }
                else
                {
                    return new ResultReturn(false);
                }
            }
            else
            {
                return new ResultReturn(false, "@请选择打开的项目");
            }
        }

        private void openEntityInternal()
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要打开的数据项");
            }
            else
            {
                ResultReturn ret = null;

                ret = OpenEntity(lst.First());

                if (ret.IsSuccess)
                {
                    ClientBroker.ViewData(lst.First());
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"无法打开指定数据");
                    }
                    else
                    {
                        ShowMessageBox(@"无法打开指定数据,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }

        /// <summary>
        ///     删除指定单据
        /// </summary>
        /// <param name="dataList"></param>
        protected virtual ResultReturn DeleteEntity(IEnumerable<Entity.EntityBase> dataList)
        {
            if (!(ModuleControler is IDeletable))
            {
                return new ResultReturn(false, @"当前模块未实现删除功能");
            }

            var handler = (IDeletable)ModuleControler;

            if (dataList != null)
            {

                foreach (var item in dataList)
                {
                    if (!handler.IsDeletable(item))
                    {
                        return new ResultReturn(false, @"部分数据无法删除,请重新选择");
                    }
                }

                var ret = handler.Delete(dataList);

                return ret;

            }
            else
            {
                return new ResultReturn(false, "@请选择删除的项目");
            }
        }

        private void deleteEntityInternal(bool enableMultiSelect)
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要删除的数据项");
            }
            else
            {
                if (!ShowMessageWithButton("该操作将删除选中的数据,是否继续?"))
                {
                    return;
                }

                ResultReturn ret = null;

                if (enableMultiSelect)
                {
                    ret = DeleteEntity(lst);
                }
                else
                {
                    ret = DeleteEntity(new[] { lst.First() });
                }

                if (ret.IsSuccess)
                {
                    ShowMessageBox("操作已成功");
                    RefreshData();
                    ExecuteSuccess(ret);
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"操作失败");
                    }
                    else
                    {
                        ShowMessageBox(@"操作失败,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }

        /// <summary>
        ///     执行指定的单据
        /// </summary>
        /// <param name="dataList"></param>
        protected virtual ResultReturn ExecuteEntity(IEnumerable<Entity.EntityBase> dataList)
        {
            if (!(ModuleControler is IExecutable))
            {
                return new ResultReturn(false, @"当前模块未实现执行功能");
            }

            var handler = (IExecutable)ModuleControler;

            if (dataList != null)
            {

                foreach (var item in dataList)
                {
                    if (!handler.IsExecutable(item))
                    {
                        return new ResultReturn(false, @"部分数据无法执行,请重新选择");
                    }
                }

                var ret = handler.Execute(dataList);

                return ret;

            }
            else
            {
                return new ResultReturn(false, "@请选择执行的项目");
            }
        }

        private void executeEntityInternal(bool enableMultiSelect)
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要执行的数据项");
            }
            else
            {
                if (!ShowMessageWithButton("该操作将执行选中的数据,是否继续?"))
                {
                    return;
                }

                ResultReturn ret = null;

                if (enableMultiSelect)
                {
                    ret = ExecuteEntity(lst);
                }
                else
                {
                    ret = ExecuteEntity(new[] { lst.First() });
                }

                if (ret.IsSuccess)
                {
                    ShowMessageBox("操作已成功");
                    RefreshData();
                    ExecuteSuccess(ret);
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"操作失败");
                    }
                    else
                    {
                        ShowMessageBox(@"操作失败,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }


        /// <summary>
        ///     反执行指定单据
        /// </summary>
        /// <param name="dataList">指定的单据列表</param>
        protected virtual ResultReturn AntiExecuteEntity(IEnumerable<Entity.EntityBase> dataList)
        {
            if (!(ModuleControler is IAntiExecutable))
            {
                return new ResultReturn(false, @"当前模块未实现反执行功能");
            }

            var handler = (IAntiExecutable)ModuleControler;

            if (dataList != null)
            {

                foreach (var item in dataList)
                {
                    if (!handler.IsAntiExecutable(item))
                    {
                        return new ResultReturn(false, @"部分数据无法反执行,请重新选择");
                    }
                }

                var ret = handler.AntiExecutable(dataList);

                return ret;

            }
            else
            {
                return new ResultReturn(false, "@请选择反执行的项目");
            }
        }

        private void antiExecuteInternal(bool enableMultiSelect)
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要反执行的数据项");
            }
            else
            {
                if (!ShowMessageWithButton("该操作将反执行选中的数据,是否继续?"))
                {
                    return;
                }

                ResultReturn ret = null;

                if (enableMultiSelect)
                {
                    ret = AntiExecuteEntity(lst);
                }
                else
                {
                    ret = AntiExecuteEntity(new[] { lst.First() });
                }

                if (ret.IsSuccess)
                {
                    ShowMessageBox("操作已成功");
                    RefreshData();
                    ExecuteSuccess(ret);
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"操作失败");
                    }
                    else
                    {
                        ShowMessageBox(@"操作失败,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }

        /// <summary>
        ///     冲红指定实体
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        protected virtual ResultReturn RedEntity(IEnumerable<EntityBase> dataList)
        {
            if (!(ModuleControler is IRedable))
            {
                return new ResultReturn(false, @"当前模块未实现冲红行功能");
            }

            var handler = (IRedable)ModuleControler;

            if (dataList != null)
            {
                foreach (var item in dataList)
                {
                    if (!handler.IsRedable(item))
                    {
                        return new ResultReturn(false, @"部分数据无法冲红,请重新选择");
                    }
                }

                var ret = handler.Red(dataList);

                return ret;

            }
            else
            {
                return new ResultReturn(false, "@请选择冲红的项目");
            }
        }

        private void redEntityInternal(bool enableMultiSelect=true)
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要冲红的数据项");
            }
            else
            {
                if (!ShowMessageWithButton("该操作将冲红选中的数据,是否继续?"))
                {
                    return;
                }

                ResultReturn ret = null;

                if (enableMultiSelect)
                {
                    ret = AntiExecuteEntity(lst);
                }
                else
                {
                    ret = AntiExecuteEntity(new[] { lst.First() });
                }

                if (ret.IsSuccess)
                {
                    ShowMessageBox("操作已成功");
                    RefreshData();
                    ExecuteSuccess(ret);
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"操作失败");
                    }
                    else
                    {
                        ShowMessageBox(@"操作失败,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }


        /// <summary>
        ///     新建一个实体,并打开编辑窗口
        /// </summary>
        protected virtual ResultReturn CreateEntity()
        {
            if (!(ModuleControler is ICreatable))
            {
                return new ResultReturn(false, @"当前模块未实现新建功能");
            }

            var handler = (ICreatable)ModuleControler;

            var ret = handler.Create();

            return ret;

            //if (newdata.IsSuccess && newdata.ReturnData is EntityBase)
            //{
            //    ClientBroker.ViewData(newdata.ReturnData);
            //}
            //else
            //{
            //    var showMsg = "新建数据失败";

            //    if (!string.IsNullOrEmpty(newdata.Message))
            //    {
            //        showMsg += (",错误信息为:\n" + newdata.Message);
            //    }

            //    MessageBox.Show(showMsg);
            //}

        }

        private void createEntityInternal()
        {
            var ret = CreateEntity();

            if (ret.IsSuccess && ret.ReturnData != null)
            {
                OpenEntity((EntityBase)ret.ReturnData);
            }
            else
            {
                if (string.IsNullOrEmpty(ret.Message))
                {
                    ShowMessageBox(@"新建数据失败");
                }
                else
                {
                    ShowMessageBox(@"新建数据失败,错误信息为:\n" + ret.Message);
                }

                ExecuteError(ret);
            }
        }

        /// <summary>
        ///     获取单据列表
        /// </summary>
        /// <param name="searchCondition">查询条件集合,key为查询条件,value为对应值</param>
        /// <param name="pageIndex">获取的页码</param>
        /// <param name="pageSize">分页中,每页的大小</param>
        /// <param name="recordCount">查询结果的总数据量</param>
        protected virtual ResultReturn<IEnumerable<EntityBase>> GetDataList(Dictionary<string, object> searchCondition, int pageIndex, int pageSize, out int recordCount)
        {
            recordCount = 0;

            if (!(ModuleControler is IGetListable))
            {
                return new ResultReturn<IEnumerable<EntityBase>>(false);
            }

            return ((IGetListable)ModuleControler).GetList(searchCondition, pageIndex, pageSize, out recordCount);

        }

        private bool getDataListInternal(int pageIndex)
        {
            if (pageIndex==1 || pageIndex==0)
            {
                dgData.IsLoadFinish = false;
                _cacheDataList.Clear();
            }

            int recordCount = 0;

            var ret = GetDataList(GetSearchCondition(), pageIndex, GetDataPageSize, out recordCount);

            if (ret.IsSuccess && ret.ReturnData != null)
            {
                foreach (var item in ret.ReturnData)
                {
                    _cacheDataList.Add(item);
                }

                if (!ret.ReturnData.Any())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        ///     审核选中的单据
        /// </summary>
        /// <param name="dataList">单据实体列表</param>
        protected virtual ResultReturn AuditEntity(IEnumerable<Entity.EntityBase> dataList)
        {
            if (!(ModuleControler is IAuditable))
            {
                return new ResultReturn(false, @"当前模块未实现审核功能"); ;
            }

            var handler = (IAuditable)ModuleControler;

            if (dataList != null)
            {

                foreach (var item in dataList)
                {
                    if (!handler.IsAuditable(item))
                    {
                        return new ResultReturn(false, @"部分数据无法审核,请重新选择");
                    }
                }

                var ret = handler.Audit(dataList);

                return ret;

                //if (ret.IsSuccess)
                //{
                //    return new ResultReturn(false, @"部分数据无法审核,请重新选择");
                //    //MessageBox.Show("审核数据成功");
                //   // return;
                //}
                //else
                //{
                //    MessageBox.Show("审核数据失败,错误信息为:\n" + ret.Message);
                //    return;
                //}

            }
            else
            {
                return new ResultReturn(false, "@请选择将进行审核的项目");
                //MessageBox.Show(@"请选择将进行审核的项目");
                //return;
            }
        }

        private void auditEntityInternal(bool enableMultiSelect)
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要审核的数据项");
            }
            else
            {
                if (!ShowMessageWithButton("该操作将审核选中的数据,是否继续?"))
                {
                    return;
                }

                ResultReturn ret = null;

                if (enableMultiSelect)
                {
                    ret = AuditEntity(lst);
                }
                else
                {
                    ret = AuditEntity(new[] { lst.First() });
                }

                if (ret.IsSuccess)
                {
                    ShowMessageBox("操作已成功");
                    RefreshData();
                    ExecuteSuccess(ret);
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"操作失败");
                    }
                    else
                    {
                        ShowMessageBox(@"操作失败,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }


        /// <summary>
        ///     反执行指定单据
        /// </summary>
        /// <param name="dataList">指定的单据列表</param>
        protected virtual ResultReturn AntiAuditEntity(IEnumerable<Entity.EntityBase> dataList)
        {

            if (!(ModuleControler is IAntiAuditable))
            {
                return new ResultReturn(false, @"当前模块未实现反审核功能");
            }

            var handler = (IAntiAuditable)ModuleControler;

            if (dataList != null)
            {
                foreach (var item in dataList)
                {
                    if (!handler.IsAntiAuditable(item))
                    {
                        return new ResultReturn(false, @"部分数据无法反审核,请重新选择");
                    }
                }

                var ret = handler.AntiAuditable(dataList);

                return ret;

            }
            else
            {
                return new ResultReturn(false, "@请选择反审核的项目");
            }
        }

        private void antiAuditEntityInternal(bool enableMultiSelect)
        {
            var lst = getSelectionList();

            if (lst.Count <= 0)
            {
                ShowMessageBox("请选择要反审核的数据项");
            }
            else
            {
                if (!ShowMessageWithButton("该操作将反审核选中的数据,是否继续?"))
                {
                    return;
                }

                ResultReturn ret = null;

                if (enableMultiSelect)
                {
                    ret = AntiAuditEntity(lst);
                }
                else
                {
                    ret = AntiAuditEntity(new[] { lst.First() });
                }

                if (ret.IsSuccess)
                {
                    ShowMessageBox("操作已成功");
                    RefreshData();
                    ExecuteSuccess(ret);
                }
                else
                {
                    if (string.IsNullOrEmpty(ret.Message))
                    {
                        ShowMessageBox(@"操作失败");
                    }
                    else
                    {
                        ShowMessageBox(@"操作失败,错误信息为:\n" + ret.Message);
                    }

                    ExecuteError(ret);
                }
            }
        }

        #endregion

        /// <summary>
        ///     强制刷新数据
        /// </summary>
        protected virtual void RefreshData()
        {
            getDataListInternal(1);
        }

        protected virtual void ExecuteError(ResultReturn errorResult)
        {
        }

        protected virtual void ExecuteSuccess(ResultReturn successResult)
        {
        }



        /// <summary>
        ///     获取数据搜索框的条件列表
        /// </summary>
        /// <returns></returns>
        protected virtual Dictionary<string, object> GetSearchCondition()
        {
            return null;
        }

        private void dgData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex<0)
            {
                return;
            }

            openEntityInternal();

            //OpenEntity(dgData.Rows[e.RowIndex]);
        }

        #region "按钮事件处理"

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openEntityInternal();
            
        }

        private void btnAddnew_Click(object sender, EventArgs e)
        {
            createEntityInternal();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            deleteEntityInternal(true);
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            executeEntityInternal(true);
        }

        private void btnAntiExecute_Click(object sender, EventArgs e)
        {
            antiExecuteInternal(true);
        }

        private void btnAudit_Click(object sender, EventArgs e)
        {
            auditEntityInternal(true);
        }

        private void btnAntiAudit_Click(object sender, EventArgs e)
        {
            antiAuditEntityInternal(true);
        }

        private void btnRed_Click(object sender, EventArgs e)
        {
            redEntityInternal(true);
        }

        #endregion

        #region 右键菜单事件

        private void tsmiOpen_Click(object sender, EventArgs e)
        {
            openEntityInternal();
        }

        private void tsmiExecute_Click(object sender, EventArgs e)
        {
            executeEntityInternal(false);
        }

        private void tsmiAntiExecute_Click(object sender, EventArgs e)
        {
            antiExecuteInternal(false);
        }

        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            deleteEntityInternal(false);
        }

        private void tsmiRed_Click(object sender, EventArgs e)
        {
            redEntityInternal(false);
        }

        private void tsmiAudit_Click(object sender, EventArgs e)
        {
            auditEntityInternal(false);
        }

        private void tsmiAntiAudit_Click(object sender, EventArgs e)
        {
            antiAuditEntityInternal(false);
        }

        #endregion

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //获取网格选中的所有行
        protected virtual List<EntityBase> getSelectionList()
        {
            if (dgData.CheckedRows.Length <= 0)
            {
                //MessageBox.Show(@"请选择将要进行删除的项目");
                return null;
            }

            var list = new List<EntityBase>(dgData.CheckedRows.Length);

            foreach (DataGridViewRow row in dgData.CheckedRows)
            {
                if (row.DataBoundItem is EntityBase)
                {
                    list.Add((EntityBase)row.DataBoundItem);
                }
            }

            if (list.Count > 0)
            {
                return list;
            }
            else
            {
                return null;
            }
        }


        private void dgContextMenu_Opening(object sender, CancelEventArgs e)
        {
            if (dgData.CurrentRow==null)
            {
                return;
            }

            var entity =(EntityBase) dgData.CurrentRow.DataBoundItem;

            tsmiOpen.Visible = ModuleControler is IOpenable && ((IOpenable)ModuleControler).IsOpenable(entity);
            tsmiDelete.Visible = ModuleControler is IDeletable && ((IDeletable)ModuleControler).IsDeletable(entity);
            tsmiAudit.Visible = ModuleControler is IAuditable && ((IAuditable)ModuleControler).IsAuditable(entity);
            tsmiAntiAudit.Visible = ModuleControler is IAntiAuditable && ((IAntiAuditable)ModuleControler).IsAntiAuditable(entity);
            tsmiExecute.Visible = ModuleControler is IExecutable && ((IExecutable)ModuleControler).IsExecutable(entity);
            tsmiAntiExecute.Visible = ModuleControler is IAntiExecutable && ((IAntiExecutable)ModuleControler).IsAntiExecutable(entity);
            tsmiRed.Visible = ModuleControler is IRedable && ((IRedable)ModuleControler).IsRedable(entity);
        }

        //当网格需要数据时,读取
        private int _pageIndex = 0;
        private void dgData_DataNeed(object sender, EventArgs e)
        {
            if (getDataListInternal(Interlocked.Increment(ref _pageIndex)))
            {
                dgData.IsLoadFinish = true;
            }
        }


    }



}
